package com.zkt.subject.domain.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/23
 * @description 本地缓存工具类
 **/

@Component
public class CacheUtil {
	
	private final Cache<String, String> localCache = CacheBuilder
			.newBuilder()
			.maximumSize(5000)
			.expireAfterWrite(10, TimeUnit.MINUTES)
			.build();
	
	/**
	 * 获取本地缓存数据（List）
	 *
	 * @param cacheKey 缓存key
	 * @param clazz    对象类
	 * @param function 缓存没有时执行的方法
	 * @return 缓存数据
	 */
	public <V> List<V> getResult(
			String cacheKey,
			Class<V> clazz,
			Function<String, List<V>> function) {
		List<V> resultList;
		
		String content = localCache.getIfPresent(cacheKey);
		
		if (StrUtil.isNotBlank(content)) {
			resultList = JSON.parseArray(content, clazz);
		} else {
			resultList = function.apply(cacheKey);
			if (CollUtil.isNotEmpty(resultList)) {
				localCache.put(cacheKey, JSON.toJSONString(resultList));
			}
		}
		
		return resultList;
	}
	
	public <K, V> Map<K, V> getResult(
			String cacheKey,
			TypeReference<Map<K, V>> typeRef,
			Function<String, Map<K, V>> function) {
		Map<K, V> resultMap;
		
		String content = localCache.getIfPresent(cacheKey);
		
		if (StrUtil.isNotBlank(content)) {
			resultMap = JSON.parseObject(content, typeRef);
		} else {
			resultMap = function.apply(cacheKey);
			if (CollUtil.isNotEmpty(resultMap)) {
				localCache.put(cacheKey, JSON.toJSONString(resultMap));
			}
		}
		
		return resultMap;
	}
	
}
